package fi.tikesos.validator.jena.builtin;

import com.hp.hpl.jena.datatypes.RDFDatatype;
import com.hp.hpl.jena.datatypes.TypeMapper;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.impl.LiteralLabel;
import com.hp.hpl.jena.reasoner.rulesys.RuleContext;
import com.hp.hpl.jena.reasoner.rulesys.builtins.BaseBuiltin;
import com.hp.hpl.jena.vocabulary.RDFS;

public class IsNotCastableAsBuiltin extends BaseBuiltin {
	/**
	 * (non-Javadoc)
	 * 
	 * @see com.hp.hpl.jena.reasoner.rulesys.Builtin#getName()
	 */
	public String getName() {
		return "notCastableAs";
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.hp.hpl.jena.reasoner.rulesys.builtins.BaseBuiltin#getArgLength()
	 */
	public int getArgLength() {
		return 2;
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.hp.hpl.jena.reasoner.rulesys.builtins.BaseBuiltin#bodyCall(com.hp.hpl.jena.graph.Node[],
	 *      int, com.hp.hpl.jena.reasoner.rulesys.RuleContext)
	 */
	public boolean bodyCall(Node[] args, int length, RuleContext context) {
		checkArgs(length, context);
		Node val = getArg(0, args, context);
		Node dt = getArg(1, args, context);
		
		if (!dt.isURI())
			return !false;
		if (val.isBlank())
			return !true;
		if (val.isLiteral()) {
			LiteralLabel ll = val.getLiteral();
			if (ll.getDatatype() != null && (!ll.isWellFormed()))
				return !false;
			if (dt.equals(RDFS.Nodes.Literal)) {
				return !true;
			} else {
				RDFDatatype dtype = TypeMapper.getInstance().getSafeTypeByName(
						dt.getURI());
				return !dtype.isValid(ll.getLexicalForm().toString());
			}
		}
		return !false;
	}
}
